<template>
  <div class="enterprise-container">
    <!--  搜索区域  -->
    <div class="search-container">
      <div class="search-label">企业名称:</div>
      <el-input v-model="params.name" clearable placeholder="请输入企业名称" class="search-main" @clear="doSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <!--  添加企业  -->
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/enterpriseAdd')">添加企业</el-button>
    </div>
    <!--  表格区域  -->
    <div class="table">
      <el-table
        :data="enterpriseList"
        style="width: 100%"
        tooltip-effect="dark"
        @expand-change="expandHandle"
      >
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320px" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="租赁截止时间" prop="endTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="scope">
                  <el-tag :type="formatInfoType(scope.row.status)">
                    {{ formartStatus(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180px" fixed="right">
                <template #default="scope">
                  <el-button size="mini" type="text" :disabled="scope.row.status===3" @click="outRent(scope.row.id)">退租</el-button>
                  <el-button size="mini" type="text" :disabled="scope.row.status!==3" @click="deleteRent(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" size="mini" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button type="text" size="mini" @click="showRent(scope.row.id)">查看</el-button>
            <el-button type="text" size="mini" @click="editEnterPrise(scope.row.id)">编辑</el-button>
            <el-button type="text" size="mini" @click="deleteEnterPrise(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页   -->
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="pageChangeHandle"
      />
    </div>
    <div class="dialog">
      <el-dialog
        title="添加合同"
        :visible.sync="dialogVisible"
        width="580px"
        :before-close="dialogCloseHandle"
      >
        <div class="form-container">
          <el-form ref="rentForm" :model="rentForm" :rules="rentFormRules" label-position="top">
            <el-form-item label="租赁楼宇" prop="buildingId">
              <el-select v-model="rentForm.buildingId" placeholder="请选择">
                <el-option
                  v-for="item in buildList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="租赁起止日期" prop="rentTime">
              <el-date-picker
                v-model="rentForm.rentTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item label="租赁合同" prop="contractId">
              <el-upload
                action="#"
                :before-upload="uploadHandleBefore"
                :http-request="uploadHandle"
              >
                <el-button size="small" type="primary">上传合同文件</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
              </el-upload>
            </el-form-item>
          </el-form>

        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogCloseHandle">取 消</el-button>
          <el-button type="primary" @click="createRent">确 定</el-button>
        </span>
      </el-dialog>
    </div>

  </div></template>

<script>
import {
  getEnterpriseListAPI,
  deleteEnterpriseAPI,
  getRentBuildListAPI,
  createRentAPI,
  getRentListAPI,
  outRentAPI,
  deleteRentAPI
} from '@/api/enterprise'
import { upLoadFileAPI } from '@/api/comment'
export default {
  name: 'Building',
  data() {
    return {
      enterpriseList: [],
      total: 0,
      params: {
        page: 1,
        pageSize: 5,
        name: ''
      },
      dialogVisible: false, // 开启对话框
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentFormRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      buildList: [] // 楼宇列表

    }
  },
  mounted() {
    this.getEnterpriseList()
  },
  methods: {
    // 删除合同
    deleteRent(rentId) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRentAPI(rentId)
        await this.getEnterpriseList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 查看合同信息
    showRent(rentId) {
      this.$router.push({
        path: '/enterpriseDetail',
        query: { 'id': rentId }
      })
    },
    // 退租
    outRent(rentId) {
      this.$confirm('确认退租吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await outRentAPI(rentId)
        await this.getEnterpriseList()
        this.$message({
          type: 'success',
          message: '退租成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 格式化tag类型
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },

    // 格式化status
    formartStatus(type) {
      const TYPEMAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return TYPEMAP[type]
    },
    // 展开数据并绑定
    async expandHandle(row, rows) {
      console.log('展开或关闭', row, rows)
      const isExpend = rows.find(item => item.id === row.id)
      if (isExpend) {
        const res = await getRentListAPI(row.id)
        row.rentList = res.data
      }
    },
    // 创建合同
    createRent() {
      this.$refs.rentForm.validate(async valid => {
        if (!valid) { return }
        const { buildingId, contractId, contractUrl, enterpriseId, type } = this.rentForm

        const fromdata = {
          'buildingId': buildingId,
          'startTime': this.rentForm.rentTime[0],
          'endTime': this.rentForm.rentTime[1],
          'contractUrl': contractUrl,
          'contractId': contractId,
          'type': type,
          'enterpriseId': enterpriseId
        }
        // const fromdata = {
        //   buildingId, contractId, contractUrl, enterpriseId, type,
        //   startTime: this.rentForm.rentTime[0],
        //   endTime: this.rentForm.rentTime[1]
        // }
        const res = await createRentAPI(fromdata)
        if (res.code === 10000) {
          this.$message.success('添加成功')
        } else {
          this.$message.error('添加失败, error' + res.msg)
        }
        // 更新列表
        await this.getEnterpriseList()
        // 关闭列表
        this.dialogVisible = false
      })
    },
    // 文件上传
    async uploadHandle(fileData) {
      // 处理FormData
      const { file } = fileData
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'contract')
      // 上传赋值
      const res = await upLoadFileAPI(formData)
      const { id, url } = res.data
      this.rentForm.contractId = id
      this.rentForm.contractUrl = url
      // 单独校验表单
      this.$refs.rentForm.validate('contractId')
    },
    // 上传前校验  支持扩展名：.doc .docx .pdf, 文件大小不超过5M
    uploadHandleBefore(file) {
      const allowFileType = ['application/doc', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5
      // if (!isPng && !isJPG && !isJpeg) {
      //   this.$message.error('上传只支持扩展名：.png .jpg .jpeg!')
      // }
      if (!allowFileType) {
        this.$message.error('上传只支持扩展名：doc .docx .pdf')
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      return allowFileType && isLt5M
    },
    // 获取楼宇列表
    async getRentBuildList() {
      const res = await getRentBuildListAPI()
      this.buildList = res.data
    },
    // 添加合同
    addRent(id) {
      this.dialogVisible = true
      this.rentForm.enterpriseId = id
      this.getRentBuildList()
    },
    dialogCloseHandle() {
      this.dialogVisible = false
    },
    // 删除企业
    deleteEnterPrise(id) {
      this.$confirm('此操作删除该企业, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteEnterpriseAPI(id)
        if (res.code === 10000) {
          this.$message.success('删除成功')
          await this.getEnterpriseList()
        } else {
          // this.$message.error('删除失败, error:' + res.msg)
          this.$message.error(`删除失败, error:${res.msg}`)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑企业
    editEnterPrise(id) {
      this.$router.push({
        path: '/enterpriseAdd',
        query: {
          id
        }
      })
    },
    async getEnterpriseList() {
      const res = await getEnterpriseListAPI(this.params)
      this.enterpriseList = res.data.rows.map(item => {
        return {
          ...item,
          rentList: [] // 每一行补充存放合同的列表
        }
      })
      this.total = res.data.total
    },
    pageChangeHandle(page) {
      this.params.page = page
      this.getEnterpriseList()
    },
    doSearch() {
      // console.log('doSearch')
      // this.params.name = ''
      this.params.page = 1
      this.getEnterpriseList()
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container{
  padding: 10px;
}
.search-container{
  display:flex;
  align-items:center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;
  .search-label{
    width: 100px;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin:10px 10px;
}
.page-container{
  padding: 4px 0;
  text-align: right;
}
.form-container{
  padding:0 80px;
}
</style>
